package com.rabbitmq.spring.config;

import com.rabbitmq.spring.api.ManualAckMessageListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author
 * @Describe 消息监听器配置
 * @date
 */
@Configuration
@Slf4j
public class MessageListenerConfig {

    @Autowired
    private CachingConnectionFactory cachingConnectionFactory;

    @Autowired
    private ManualAckMessageListener manualAckMessageListener;

    @Bean
    public SimpleMessageListenerContainer simpleMessageListenerContainer() {
        // amqp-client会创建一个固定大小的连接池（默认size：Runtime.getRuntime().availableProcessors() * 2）。如果需要使用大量的连接，可以在CachingConnectionFactory中设置一个executor 。
        // cachingConnectionFactory.setExecutor("ExecutorService or ThreadPoolTaskExecutor");
        SimpleMessageListenerContainer simpleMessageListenerContainer = new SimpleMessageListenerContainer(cachingConnectionFactory);
        // 设置并发消费者数
        simpleMessageListenerContainer.setConcurrentConsumers(1);
        // 设置最大并发消费者数
        simpleMessageListenerContainer.setMaxConcurrentConsumers(1);
        // 设置确认方式为手动
        simpleMessageListenerContainer.setAcknowledgeMode(AcknowledgeMode.MANUAL);

        // 设置监听的队列名称方式一, 如果同时设置多个以,逗号隔开，注意设置的队列都是必须已经存在的
        // simpleMessageListenerContainer.setQueueNames("spring_kinson_queue_direct_publishDirectQueueManualAck");
        // 设置多个
        // simpleMessageListenerContainer.setQueueNames("queue","queue2","queue3");

        // 设置监听的队列名称方式二
        // simpleMessageListenerContainer.setQueues(new Queue("spring_kinson_queue_direct_publishDirectQueueManualAck"));
        // 设置多个
        // simpleMessageListenerContainer.setQueues(new Queue("queue"), new Queue("queue2"), new Queue("queue3"));

        // 设置监听的队列名称方式三
        // simpleMessageListenerContainer.addQueueNames("spring_kinson_queue_direct_publishDirectQueueManualAck");
        // 设置多个
        // simpleMessageListenerContainer.addQueueNames("queue","queue2","queue3");

        // 设置监听的队列名称方式四
        simpleMessageListenerContainer.addQueues(new Queue("spring_kinson_queue_direct_publishDirectQueueManualAck"));
        // 设置多个
        // simpleMessageListenerContainer.addQueues(new Queue("queue"), new Queue("queue2"), new Queue("queue3"));

        // 设置消息监听器(此时所有被监听的队列都会被设置的消息监听器统一处理，未设置则由对应的消费端消费)
        simpleMessageListenerContainer.setMessageListener(manualAckMessageListener);

        return simpleMessageListenerContainer;
    }
}
